package com.tsugun.mediaplayer.view.widget

import android.animation.Animator
import android.animation.TimeInterpolator
import android.animation.ValueAnimator
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.view.animation.DecelerateInterpolator
import android.widget.RelativeLayout

/**
 * 自定义可滑动 RelativeLayout
 * Created by shize on 2017/9/6.
 */
class SlidingRelativeLayout @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : RelativeLayout(context, attrs, defStyleAttr), GestureDetector.OnGestureListener {

    private lateinit var mContent: View // 布局主要内容
    private lateinit var mBackground: View  // 布局背景

    private var mWidth = 0 // 控件宽度
    private var mHeight = 0 // 控件高度

    private var mLastX = 0 // 上一次指尖位置
    private var isClose = false // 是否关闭

    private val mGestureDetector: GestureDetector = GestureDetector(context, this)

    private var mOnSlidingListener: OnSlidingListener? = null // 监听事件

    override fun onFinishInflate() {
        super.onFinishInflate()
        initChildView()
    }

    /**
     * 初始化 view
     */
    private fun initChildView() {
        mBackground = getChildAt(0)
        mContent = getChildAt(1)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        mWidth = r - l
        mHeight = b - t
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event!!.action == MotionEvent.ACTION_UP) {
            val distance = (mContent.layoutParams as LayoutParams).marginStart
            Log.d("SRLTouch", "$distance")
            // 判断滑动后的状态
            isClose = Math.abs(distance) >= mWidth / 5f
            doAnimation(distance)
            return true
        }
        return mGestureDetector.onTouchEvent(event)
    }

    override fun onDown(p0: MotionEvent?): Boolean {
        if (p0!!.x > mWidth - mContent.width) {
            // 当触摸点在 mContent 上时，进行事件拦截
            mLastX = p0.x.toInt()
            onTouchDown()
            return true
        }
        return false
    }

    override fun onShowPress(p0: MotionEvent?) {

    }

    override fun onSingleTapUp(p0: MotionEvent?): Boolean {
        return false
    }

    override fun onLongPress(p0: MotionEvent?) {

    }

    override fun onScroll(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
        val moveDistance = (p1!!.x - mLastX).toInt()
        moveContent(moveDistance)

        mLastX = p1.x.toInt()
        return true
    }

    /**
     * 移动内容
     */
    private fun moveContent(moveDistance: Int) {
        val lpContent: LayoutParams = mContent.layoutParams as LayoutParams
        lpContent.marginStart += moveDistance
        lpContent.marginEnd += -moveDistance
        mContent.layoutParams = lpContent

        backgroundAlpha(lpContent.marginStart)
    }

    /**
     * 指定内容位置
     */
    private fun appointContent(appointMargin: Int) {
        val lpContent: LayoutParams = mContent.layoutParams as LayoutParams
        lpContent.marginStart = appointMargin
        lpContent.marginEnd = -appointMargin
        mContent.layoutParams = lpContent

        backgroundAlpha(lpContent.marginStart)
    }

    /**
     * 背景透明度设置
     */
    private fun backgroundAlpha(marginStart: Int) {
        if (marginStart < 0) {
            mBackground.alpha = (mWidth.toFloat() + marginStart) / mWidth + 0.02f
            return
        }
        mBackground.alpha = (mWidth.toFloat() - marginStart) / mWidth + 0.02f
    }

    override fun onFling(p0: MotionEvent?, p1: MotionEvent?, p2: Float, p3: Float): Boolean {
        return false
    }

    /**
     * 执行动画
     */
    private fun doAnimation(distance: Int) {
        val animator: ValueAnimator
        if (isClose) {
            if (distance < 0) {
                animator = ValueAnimator.ofInt(distance, -mWidth)
            } else {
                animator = ValueAnimator.ofInt(distance, mWidth)
            }
        } else {
            animator = ValueAnimator.ofInt(distance)
        }
        animator.interpolator = DecelerateInterpolator(1f) as TimeInterpolator?
        animator.duration = 300
        animator.addUpdateListener { animator ->
            val value = animator.animatedValue as Int
            if (isClose) {
                appointContent(value)
            } else {
                appointContent(distance - value)
            }
        }
        animator.addListener(object : Animator.AnimatorListener {
            override fun onAnimationRepeat(p0: Animator?) {
            }

            override fun onAnimationEnd(p0: Animator?) {
                onEndOfAnimation()
                if (isClose) {
                    onClose()
                    return
                }
                onOpen()
            }

            override fun onAnimationCancel(p0: Animator?) {
            }

            override fun onAnimationStart(p0: Animator?) {

            }
        })
        animator.start()
    }

    /**
     * 当关闭时
     */
    private fun onClose() {

    }

    /**
     * 当开启时
     */
    private fun onOpen() {

    }

    /**
     * 结束动画调用
     */
    private fun onEndOfAnimation() {
        if (mOnSlidingListener == null) {
            return
        }
        mOnSlidingListener!!.onAnimationEnd(isClose)
    }

    /**
     * 设置按下回调
     */
    private fun onTouchDown() {
        if (mOnSlidingListener != null) {
            mOnSlidingListener!!.onDown()
        }
    }

    /**
     * 监听注册
     */
    fun setOnSlidingListener(listener: OnSlidingListener) {
        mOnSlidingListener = listener
    }

    /**
     * 事件监听器
     */
    interface OnSlidingListener {
        fun onDown()
        fun onAnimationEnd(isClose: Boolean)
    }
}
